package com.example.administrator.exkotlin.multithread


import android.app.Activity
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import androidx.core.app.NotificationCompat

import android.util.Log
import android.view.View
import com.example.administrator.exkotlin.MainActivity
import com.example.administrator.exkotlin.R
import kotlinx.android.synthetic.main.activity_multithread.*
import java.lang.ref.WeakReference


/**
 * 多线程编程例子
 * */
class MultithreadActivity : AppCompatActivity(), View.OnClickListener {


    private val TAG = "MultithreadActivity"
    private lateinit var weak: WeakReference<Activity>
    lateinit var handler: Handler
    lateinit var asyncTask: MutiAsyncTask
    val msg1 = 0x101
    val delayTime: Long = 100

    lateinit var myservice: MyService
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_multithread)
        val stringExtra = intent.getStringExtra("test")
        Log.i(TAG,stringExtra)
        initData()
    }

    private fun initData() {
        weak = WeakReference<Activity>(this)
        //初始化handler
        handler = MutiHandler(weak)
        //发送message
        btn_handler.setOnClickListener(this)
        btn_start_async.setOnClickListener(this)
        btn_stop.setOnClickListener(this)
        btn_start_service.setOnClickListener(this)
        btn_bind_service.setOnClickListener(this)
        btn_stop_service.setOnClickListener(this)
        btn_unbind_service.setOnClickListener(this)
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.btn_handler -> {
                Log.i(TAG, "开始")
                val message = handler.obtainMessage()
                message.what = msg1
                handler.sendMessageDelayed(message, delayTime)
            }
            R.id.btn_start_async -> {
                if (::asyncTask.isInitialized) {
                    asyncTask.cancel(true)
                }
                asyncTask = MutiAsyncTask(weak)
                asyncTask.execute(pb_ui.progress)
            }
            R.id.btn_stop -> {
                if (::asyncTask.isInitialized) {
                    asyncTask.cancel(true)
                }
                handler.removeCallbacksAndMessages(null)
            }
            R.id.btn_start_service -> {
                startService(Intent(this, MyService::class.java))
            }
            R.id.btn_stop_service -> {
                stopService(Intent(this, MyService::class.java))
            }
            R.id.btn_bind_service -> {
                bindService(Intent(this, MyService::class.java), conection, Context.BIND_AUTO_CREATE)
            }
            R.id.btn_unbind_service -> {
                if (MyService.isBinding) {
                    myservice.stopThread()
                    unbindService(conection)
                }

            }
        }

    }

    private val conection = object : ServiceConnection {

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            Log.i(TAG, "服务绑定成功： " + name?.toString())
            MyService.isBinding = true
            val mybind = service as MyService.MyBind
            myservice = mybind.getService()

            tv_service_status.text = myservice.getServiceStatus()
            myservice.startThread(serviceCallback)
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            Log.i(TAG, "服务解绑成功： " + name?.toString())
            MyService.isBinding = false
        }

    }
    //监听service进度
    private val serviceCallback = object : MyService.ServiceCallback {
        override fun porgeress(progress: Int) {
            runOnUiThread {
                tv_service_status.text = "进度：${progress}"
            }
        }
    }


    //更新ui
    fun updataUi(): Boolean {
        var result = true
        var nowProgress = ++pb_ui.progress
        if (nowProgress >= pb_ui.max) {
            result = false
            nowProgress = 0
        }
        pb_ui.progress = nowProgress
        Log.i(TAG, "updataingUi:   ${nowProgress}")
        return result
    }

    override fun onDestroy() {
        super.onDestroy()
        finish()
        //移除handler消息
        handler.removeCallbacksAndMessages(null)
        //停止AsyncTask
        if (::asyncTask.isInitialized && !asyncTask.isCancelled) {
            asyncTask.cancel(true)
        }
        //解绑服务
        if (::myservice.isInitialized && MyService.isBinding) {
            unbindService(conection)
        }
        //关闭服务
        if (MyService.isRunning) {
            stopService(Intent(this, MyService::class.java))
        }
        Log.i(TAG, "onDestroy")

    }
}
